"""
A simple demo for opencv operator encapsulation and for api test
"""
import os
import time
import cv2
import numpy as np
import requests

from ai.models import Models
from ai.utils.config import docker_path, ai_url
from ai.utils.docker_util import create_container, check_container

INTERPOLATIONS = {
    '双线性插值': cv2.INTER_LINEAR,
    '最近邻插值': cv2.INTER_NEAREST,
    '双三次插值': cv2.INTER_CUBIC,
    '区域重采样': cv2.INTER_AREA
}

CHANNELS = {
    'GRAY': cv2.COLOR_BGR2GRAY,
    'HSV': cv2.COLOR_BGR2HSV,
}


def resize(img, width: int, height: int, inter_method: str):
    current_img = cv2.resize(img, (int(width), int(height)))
    return current_img, {'width': width, 'height': height, 'inter_method': inter_method}


# ai算子
def algo(img, ai_type, model_name):
    model = Models.objects.get(name=model_name)

    # # 判断是否需要开启容器
    # if not check_container():
    #     create_container()
    #     time.sleep(5)

    test_result_path = 'runs/' + model.name + '/test'  # 测试结果路径
    data_path = test_result_path + '/test.jpg'  # 测试图片路径
    model_type = model.type
    model_weights = model.weights
    # 访问
    url = ai_url
    params = {
        'model_type': model_type,
        'data_path': data_path,
        'test_result_path': test_result_path,
        'model_weights': model_weights
    }

    dir_path = os.path.join(docker_path, test_result_path)
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    file_path = os.path.join(dir_path, "test.jpg")
    cv2.imwrite(file_path, img)
    print(f"✅ `url` 执行完成，结果: {url}")

    res = requests.get(url=url, params=params)
    print(res.text)
    # 训练完成
    picture_path = os.path.join(docker_path, test_result_path, 'exp', 'test.jpg')
    # image2byte
    with open(picture_path, "rb") as f:
        byte_data = f.read()
    # byte2numpy
    image = np.asarray(bytearray(byte_data), dtype="uint8")
    current_img = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return current_img, {'model_name': model_name}


def changeChannels(img, channels):
    current_img = cv2.cvtColor(img, CHANNELS[channels])
    return current_img, {'channels': channels}
